package com.zzyq.pc.mongodb.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.aggregation.Accumulator;
import org.mongodb.morphia.aggregation.AggregationPipeline;
import org.mongodb.morphia.aggregation.Group;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.Sort;

import com.mongodb.AggregationOptions;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.mongodb.model.MongodbDate;
import com.zzyq.pc.utils.MongoHelper;

public class MongodbMonitoring {
	MongoHelper mongodb = MongoHelper.getInstance();
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	Calendar lastDate = Calendar.getInstance();
	
	
	/**
	 * 监控——舆情概况
	 * @param pageView 分页参数
	 * @param ifmIds 方案ID 
	 * @param startTime 开始时间
	 * @param endTime	结束时间
	 */
	public List<MongodbDate> findGeneralSituation(Class<?> MongoDate,PageView pageView,List<String> ifmIds,
			Date startTime,Date endTime){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		int pageIndex = pageView.getPageNow();
		int pageSize = pageView.getPageSize();
		Query<?> query = mongodb.getDatastore().createQuery(MongoDate);
		query.field("ifmId").in(ifmIds);
		if (null != endTime && null != startTime) {
			//给结束时间加一天
			Calendar ca = Calendar.getInstance();
			ca.setTime(endTime);
			ca.add(Calendar.DATE, 1);
			endTime = ca.getTime();
			query.field("releaseTime").lessThan(endTime);
			query.field("releaseTime").greaterThanOrEq(startTime);
		}
		//排序
		//query.order(Sort.descending("sort_timestamp")).order(Sort.descending("releaseTime"));
		//聚合
		AggregationPipeline peline = mongodb.getDatastore().createAggregation(MongoDate).match(query)
				.sort(Sort.ascending("sort_timestamp")).sort(Sort.ascending("releaseTime"))
				.group(Group.id(Group.grouping("groupId")),
						Group.grouping("groupId", Group.first("groupId")),
						Group.grouping("ifmId", Group.first("ifmId")),
						Group.grouping("ifmName", Group.first("ifmName")),
						Group.grouping("articleId", Group.first("articleId")),
						Group.grouping("articleType",Group.first("articleType")),
						Group.grouping("title", Group.first("title")),
						Group.grouping("url", Group.first("url")),
						Group.grouping("author", Group.first("author")),
						Group.grouping("releaseTime",Group.first("releaseTime")),
						Group.grouping("weiboSourceContent",Group.first("weiboSourceContent")),
						Group.grouping("weiboContent",Group.first("weiboContent")),
						Group.grouping("weiboBlogger",Group.first("weiboBlogger")),
						Group.grouping("websiteName",Group.first("websiteName")),
						Group.grouping("original", Group.first("original")),
						Group.grouping("timestamp", Group.first("timestamp")),
						Group.grouping("sort_timestamp",Group.first("sort_timestamp")),
						Group.grouping("reprintNumb",new Accumulator("$sum", 1)))
				.sort(Sort.descending("sort_timestamp")).sort(Sort.descending("releaseTime"))
				.skip(pageIndex * pageSize - pageSize).limit(pageSize);
		Iterator<?> iterator = peline.aggregate(MongoDate,AggregationOptions.builder().allowDiskUse(true).build());
		while (iterator.hasNext()) {
			MongodbDate date = (MongodbDate)iterator.next();
			list.add(date);
		}
		return list;
	}
	
	/**
	 * 监控——媒体舆情
	 * @param pageView 分页参数
	 * @param ifmIds 方案ID
	 * @param startTime 开始时间
	 * @param endTime	结束时间
	 * @param articleType 媒体新闻
	 */
	public List<MongodbDate> findMedia(Class<?> MongoDate,PageView pageView,List<String> ifmIds,Date startTime,
			Date endTime,String articleType){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		int pageIndex = pageView.getPageNow();
		int pageSize = pageView.getPageSize();
		Query<?> query = mongodb.getDatastore().createQuery(MongoDate);
		query.field("ifmId").in(ifmIds).field("articleType").equal(articleType);
		if (null != endTime && null != startTime) {
			//给结束时间加一天
			Calendar ca = Calendar.getInstance();
			ca.setTime(endTime);
			ca.add(Calendar.DATE, 1);
			endTime = ca.getTime();
			query.field("releaseTime").lessThan(endTime);
			query.field("releaseTime").greaterThanOrEq(startTime);
		}
		//排序
		//query.order(Sort.descending("sort_timestamp")).order(Sort.descending("releaseTime"));
		//聚合
		AggregationPipeline peline = mongodb.getDatastore().createAggregation(MongoDate).match(query)
				.sort(Sort.ascending("sort_timestamp")).sort(Sort.ascending("releaseTime"))
				.group(Group.id(Group.grouping("groupId")),
						Group.grouping("groupId", Group.first("groupId")),
						Group.grouping("ifmId", Group.first("ifmId")),
						Group.grouping("ifmName", Group.first("ifmName")),
						Group.grouping("articleId", Group.first("articleId")),
						Group.grouping("articleType",Group.first("articleType")),
						Group.grouping("title", Group.first("title")),
						Group.grouping("url", Group.first("url")),
						Group.grouping("author", Group.first("author")),
						Group.grouping("releaseTime",Group.first("releaseTime")),
						Group.grouping("weiboSourceContent",Group.first("weiboSourceContent")),
						Group.grouping("weiboContent",Group.first("weiboContent")),
						Group.grouping("weiboBlogger",Group.first("weiboBlogger")),
						Group.grouping("websiteName",Group.first("websiteName")),
						Group.grouping("original", Group.first("original")),
						Group.grouping("timestamp", Group.first("timestamp")),
						Group.grouping("sort_timestamp",Group.first("sort_timestamp")),
						Group.grouping("reprintNumb",new Accumulator("$sum", 1)))
				.sort(Sort.descending("sort_timestamp")).sort(Sort.descending("releaseTime"))
				.skip(pageIndex * pageSize - pageSize).limit(pageSize);
		Iterator<?> iterator = peline.aggregate(MongoDate,AggregationOptions.builder().allowDiskUse(true).build());
		while (iterator.hasNext()) {
			MongodbDate date = (MongodbDate)iterator.next();
			list.add(date);
		}
		return list;
	}
	/**
	 * 监控——网络舆情
	 * @param MongoDate
	 * @param pageView  分页参数
	 * @param ifmIds	方案ID
	 * @param startTime	开始时间
	 * @param endTime	结束时间
	 * @param articleType	网络类型
	 */
	public List<MongodbDate> findNetwork(Class<?> MongoDate,PageView pageView,List<String> ifmIds,Date startTime,
			Date endTime,List<String> articleType){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		int pageIndex = pageView.getPageNow();
		int pageSize = pageView.getPageSize();
		Query<?> query = mongodb.getDatastore().createQuery(MongoDate);
		query.field("ifmId").in(ifmIds);
		query.field("articleType").in(articleType);
		if (null != endTime && null != startTime) {
			//给结束时间加一天
			Calendar ca = Calendar.getInstance();
			ca.setTime(endTime);
			ca.add(Calendar.DATE, 1);
			endTime = ca.getTime();
			query.field("releaseTime").lessThan(endTime);
			query.field("releaseTime").greaterThanOrEq(startTime);
		}
		//排序
		//query.order(Sort.descending("sort_timestamp")).order(Sort.descending("releaseTime"));
		//聚合
		AggregationPipeline peline = mongodb.getDatastore().createAggregation(MongoDate).match(query)
				.sort(Sort.ascending("sort_timestamp")).sort(Sort.ascending("releaseTime"))
				.group(Group.id(Group.grouping("groupId")),
						Group.grouping("groupId", Group.first("groupId")),
						Group.grouping("ifmId", Group.first("ifmId")),
						Group.grouping("ifmName", Group.first("ifmName")),
						Group.grouping("articleId", Group.first("articleId")),
						Group.grouping("articleType",Group.first("articleType")),
						Group.grouping("title", Group.first("title")),
						Group.grouping("url", Group.first("url")),
						Group.grouping("author", Group.first("author")),
						Group.grouping("releaseTime",Group.first("releaseTime")),
						Group.grouping("weiboSourceContent",Group.first("weiboSourceContent")),
						Group.grouping("weiboContent",Group.first("weiboContent")),
						Group.grouping("weiboBlogger",Group.first("weiboBlogger")),
						Group.grouping("websiteName",Group.first("websiteName")),
						Group.grouping("original", Group.first("original")),
						Group.grouping("timestamp", Group.first("timestamp")),
						Group.grouping("sort_timestamp",Group.first("sort_timestamp")),
						Group.grouping("reprintNumb",new Accumulator("$sum", 1)))
				.sort(Sort.descending("sort_timestamp")).sort(Sort.descending("releaseTime"))
				.skip(pageIndex * pageSize - pageSize).limit(pageSize);
		Iterator<?> iterator = peline.aggregate(MongoDate,AggregationOptions.builder().allowDiskUse(true).build());
		while (iterator.hasNext()) {
			MongodbDate date = (MongodbDate)iterator.next();
			list.add(date);
		}
		return list;
	}
	
	/**
	 * 中周舆情搜索
	 * @param entity
	 * @param pageView
	 * @param articleType
	 * @param title
	 */
	public List<MongodbDate> findzhongzhouSeek(Class<?> entity,PageView pageView,String articleType,
			String title,List<String> ifmIds,String author) {
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		int pageIndex = pageView.getPageNow();
		int pageSize = pageView.getPageSize();
		DBCollection tion = mongodb.getDatastore().getCollection(entity);
		//条件
		BasicDBObject query = new BasicDBObject();
		query.put("ifmId", new BasicDBObject("$in",ifmIds));
		if (StringUtils.isNotBlank(articleType)) {
			query.put("articleType", articleType);
		}
		//标题和微博原文与微博转发文
		if (StringUtils.isNotBlank(title)) {
			//模糊匹配
			Pattern pattern = Pattern.compile(".*"+title.trim()+".*$", Pattern.CASE_INSENSITIVE);
			//查询媒体、微信、论坛标题字段，查询微博原文和转发文字段
			query.append("$or", new BasicDBObject[]{
					new BasicDBObject("title",pattern)
			,new BasicDBObject("weiboContent",pattern)
			,new BasicDBObject("weiboSourceContent",pattern)});
		}
		//作者和博主
		if (StringUtils.isNotBlank(author)) {
			//模糊匹配
			Pattern pattern = Pattern.compile(".*"+author.trim()+".*$", Pattern.CASE_INSENSITIVE);
			query.append("$or",new BasicDBObject[]{new BasicDBObject("author", pattern),
					new BasicDBObject("weiboBlogger", pattern)});
		}
		//统计本次查询条数
		int count = tion.find(query).count();
		//排序分页查询
		DBCursor sor = tion.find(query).sort(new BasicDBObject("releaseTime",-1))
				.skip(pageIndex * pageSize - pageSize).limit(pageSize);
		while (sor.hasNext()) {
			DBObject object = sor.next();
			MongodbDate date = new MongodbDate();
			date.setId(String.valueOf(object.get("_id")));
			date.setIfmId(String.valueOf(object.get("ifmId")));
			date.setArticleId(String.valueOf(object.get("articleId")));
			date.setGroupId(String.valueOf(object.get("groupId")));
			date.setArticleType(String.valueOf(object.get("articleType")));
			date.setWebsiteName(String.valueOf(object.get("websiteName")));
			date.setAuthor(String.valueOf(object.get("author")));
			date.setTitle(String.valueOf(object.get("title")));
			date.setWeiboContent(String.valueOf(object.get("weiboContent")));
			date.setWeiboSourceContent(String.valueOf(object.get("weiboSourceContent")));
			date.setWeiboBlogger(String.valueOf(object.get("weiboBlogger")));
			date.setWebsiteName(String.valueOf(object.get("websiteName")));
			Date time2 = (Date)object.get("releaseTime");
			date.setReleaseTime(time2);
			date.setUrl(String.valueOf(object.get("url")));
			list.add(date);
		}
		if (count>0 && list.size()>0) {
			list.get(0).setCount(count);
		}
		return list;
	}
	
	/**
	 * 查询微信单个数据接口
	 * @param entity
	 * @param articleId
	 * @param ifmId
	 */
	public MongodbDate findSingle(Class<?> entity,String articleId,String ifmId){
		MongodbDate date = new MongodbDate();
		Query<?> query = mongodb.getDatastore().createQuery(entity);
		Iterator<?> tor = query.field("articleId").equal(articleId).field("ifmId").equal(ifmId).iterator();
		while (tor.hasNext()) {
			date = (MongodbDate)tor.next();
		}
		return date;
	}
	
	/**
	 * 根据唯一Id集合查询接口
	 * @param entity
	 * @param articleId
	 * @return
	 */
	public List<MongodbDate> findByArticleId(Class<?> entity,List<String> Id){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		Query<?> query = mongodb.getDatastore().createQuery(entity);
		Iterator<?> iterator = query.field("_id").in(Id).order(Sort.descending("releaseTime")).iterator();
		while (iterator.hasNext()) {
			MongodbDate date = (MongodbDate)iterator.next();
			list.add(date);
		}
		return list;
	}
	/*public static void main(String[] args) throws ParseException {
		MongodbMonitoring mongodb = new MongodbMonitoring();
		Calendar lastDate = Calendar.getInstance();
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		List<String> ifmIds = new ArrayList<>();
		//ifmIds.add("233");
		ifmIds.add("290");
		PageView pageView = new PageView();
		pageView.setPageNow(1);
		pageView.setPageSize(10);
		long l = System.currentTimeMillis();
		Date endTime  = new Date(l);
		lastDate.add(Calendar.DATE, -90);
		Date startTime = new Date(lastDate.getTime().getTime());
		List<String> articleType = new ArrayList<String>();
		articleType.add("WeiXin");
		articleType.add("Micro");
		articleType.add("BBS");
		String title = null;
		long ll = System.currentTimeMillis();
		list = mongodb.findzhongzhouSeek(MongodbDate.class,pageView,articleType,title,ifmIds);
		System.out.println(System.currentTimeMillis()-ll);
		System.out.println(list.size());
		for (MongodbDate mlist : list) {
			System.out.println(mlist);
		}
	}*/


}
